package com.example.scala.chapter2

import java.io._
import java.lang.Thread.sleep
import java.net.Socket
import java.nio.charset.StandardCharsets


/**
 *
 * Description:
 *
 * Create by lucienoz on 2021/10/13.
 * Copyright © 2021 lucienoz. All rights reserved.
 */
object chapter10 {
  def main(args : Array[String]) : Unit = {
    val client : Socket = new Socket("localhost",19999)
    val clientInputStream : InputStream = client.getInputStream
    val reader = new BufferedReader ( new InputStreamReader ( clientInputStream, StandardCharsets.UTF_8 ) )

    var flag : Boolean = true
    while(flag) {

      val charArr : Array[Char] = new Array[Char]( 1024 )
      val i : Int = reader.read ( charArr ) //调用此方法时应确保，对面的输出流没有关闭否则报错

      if(i == -1) {
        flag = false
      }else{
        print(1)
        charArr.foreach(char => if(char != 0) print(char))

      }
    }
    println()
    client.shutdownInput()


    val clientoutputStream : OutputStream = client.getOutputStream
    val bufferedWriter = new BufferedWriter ( new OutputStreamWriter ( clientoutputStream, StandardCharsets.UTF_8 ) )
    bufferedWriter.write("client"+client.getLocalSocketAddress+"\n")
    bufferedWriter.flush()
    client.shutdownOutput()

    Thread.sleep(5000)
    client.close()




  }

}
